<template>
    <div style="min-height: 30vh;background: white;" ref="comment"><!--训后考试-->
      <!-- 列表 -->
      <div class="scroll-box" style="margin-top: 10px;">
              <div class="list-box">
                  <div class="item-box" @click="beforeToCre(item)" v-for="(item, index) in certificateList" :key="index">
                    <div>
                      <div style="color: #7F7F7F; font-size: 12px;margin-bottom: 8px;">{{ $t('exam_time')}}：{{item.startTime || '--'}}</div>
                      <div>
                        <span v-if="item.status===0" style="color: #F59A23;margin-left: -5px;">【{{ $t('cos_time_stop') }}】</span>
                        <span v-if="item.status===1" style="margin-left: -5px;">【{{ $t('cos_app_not_started') }}】</span>
                        <span v-if="item.status===2" style="color: #70B603;margin-left: -5px;"> 【 {{ $t('cos_app_inprogress') }}】</span>
                        <span>{{item.type===0? $t('offline_training_theoretical_exams'):item.type ===1? $t('offline_training_practical_examination') : '--'}}</span>
                      </div>
                    </div>
                    <div class="box-right">
                      <span v-if="item.pass===1" style="color:#70B603;border:1px solid #70B603;padding: 3px 10px;border-radius: 5px;">{{ $t('cos_app_pass') }}</span>
                      <span  v-if="item.pass===0" style="color:#D90056;border:1px solid #D90056;padding: 3px 10px;border-radius: 5px;">{{ $t('cos_app_flunk') }}</span>
                      <van-icon name="arrow" color="#8A8A8A" style="margin-left: 5px;"/>
                    </div>
                  </div>
              </div>
              <!--暂无数据-->
              <div v-if="!isLoading && total === 0" style="height:100%;">
                  <div class="box-table" style="width:100%;height:100%;">
                      <div class="box-table-cell" style="text-align: center;">
                          <div class="no-data">
                              <img src="../../../static/images/no-data.png" alt=""/>
                              <p class="color999">{{ $t("no_data") }}</p>
                          </div>
                      </div>
                  </div>
              </div>
              <common-loading :isLoading="isLoading"></common-loading>
      </div>
      <van-popup v-model="show">
        <div v-html="iframeSrc" @click="show=false" class="myCertifica"></div>
      </van-popup>
        <van-dialog
        v-model="examTip"
        show-cancel-button
        :title=" currentItem ? currentItem.title : ''"
        :confirmButtonText="$t('start_the_exam')"
        :cancelButtonText="$t('cancel')"
        @confirm="startExam"
        >
            <div style="font-size: 14px; color: #1a1a1a;">
                <div>{{ $t('start_the_exam') }}：{{currentItem.startTime}}</div>
                <div style="padding: 10px 0 0;">{{ $t('exam_duration')}}：{{currentItem.duration}}{{$t('mod_time_minute')}}</div>
                <div style="padding: 10px 0 0;word-wrap:break-word;">{{ $t('tota_score_of_test_paper')}}：{{ currentItem.maxScore }} {{$t('points')}}</div>
                <div style="padding: 10px 0 0;word-wrap:break-word;">{{ $t('mod_passing_score')}}：{{ currentItem.passScore }} {{$t('points')}}</div>
            </div>
        </van-dialog>
    </div>
</template>

<script>
import { Popup, Notify, Toast } from 'vant';
export default {
    name: 'postTrainingExamination',
    components: {
        Popup,
        vanToast: Toast,
        [Notify.Component.name]: Notify.Component
    },
    data() {
        return {
            isLoading: false,
            id: this.$route.query.id,
            certificateList: [],
            iframeSrc: '',
            show: false,
            maxPageNo: null,
            examTip: false,
            total: null,
            currentItem: {},
            locale: {
                'en': 'en-US',
                'cn': 'zh-CN',
                'hk': 'zh-TW'
            },
            token: window.localStorage.getItem('token'),
            finished: false
        };
    },
    props: ['data'],
    methods: {
        getFreshDetail(option) {
            this.isLoading = true;
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/train/list`,
                params: {
                    pageNo: this.pageNo,
                    pageSize: 9999,
                    itmId: this.$route.query.id
                }
            }).then(res => {
                if (res && res.status === 200) {
                    this.isLoading = false;
                    if (option && option === 'refresh') {
                        this.certificateList = res.data.results || [];
                    } else {
                        this.certificateList = this.certificateList.concat(res.data.results);
                    }
                }
                this.maxPageNo = res.data.totalPage;
                this.total = res.data.totalRecord;
                this.isLoading = false;
            }).catch(err => {
                console.log('err', err);
            });
        },
        startExam() {
            this.goToDetail();
        },
        goToDetail() {
            if (process.env.NODE_ENV === 'production_app') {
                if (window.plus) {
                    var ws = window.plus.webview.currentWebview();
                    // var embed = window.plus.webview.create(this.appUrl + `/app/pk-trainee/index.html?token=${this.token}#/pk/square?lang=${this.locale[this.$i18n.locale]}`);
                    // 如果真机调试就解注下面两行，注释第三行
                    // this.appUrl = 'http://192.168.31.80:8888';
                    // var embed = window.plus.webview.create(this.appUrl + `/#/examCertifiedDetail/${this.data.appTkhId}/${this.currentItem.resId}/${this.$route.query.id}?examIframeToken=${this.token}&examIframeLang=${this.locale[this.$i18n.locale]}&examIframeUsrId=${window.localStorage.getItem('usrSteUsrId')}`);
                    var embed = window.plus.webview.create(this.appUrl + `/mobile/#/examCertifiedDetail/${this.data.appTkhId}/${this.currentItem.resId}/${this.$route.query.id}?examIframeToken=${this.token}&examIframeLang=${this.locale[this.$i18n.locale]}&examIframeUsrId=${window.localStorage.getItem('usrSteUsrId')}`);
                    embed.onclose = () => this.embedClose();
                    ws.append(embed);
                } else {
                    document.addEventListener('plusready', () => {
                        this.isAPP = true;
                        var ws = window.plus.webview.currentWebview();
                        var embed = window.plus.webview.create(this.appUrl + `/mobile/#/examCertifiedDetail/${this.data.appTkhId}/${this.currentItem.resId}/${this.$route.query.id}?examIframeToken=${this.token}&examIframeLang=${this.locale[this.$i18n.locale]}&examIframeUsrId=${window.localStorage.getItem('usrSteUsrId')}`);
                        embed.onclose = () => this.embedClose();
                        ws.append(embed);
                    }, false);
                }
            } else {
                this.$router.push(`/examCertifiedDetail/${this.data.appTkhId}/${this.currentItem.resId}/${this.$route.query.id}`);
            }
        },
        embedClose() {
            this.certificateList = [];
            this.getFreshDetail();
        },
        beforeToCre(item) {
            // 人脸信息采集 - 校验人脸信息是否可用：进入认证培训课程详情之前需要校验人脸信息是否可用
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/user-face-gather/check-user-face`,
                params: {
                    busId: item.resId,
                    type: 'ONLINE_COURSE'
                }
            }).then(res => {
                if (res.data.code === '500') {
                    Toast({message: res.data.msg, forbidClick: true});
                } else {
                    this.toCre(item);
                }
            }).catch(err => {
                console.log('err:---', err.response.data);
            });
        },
        toCre(item) {
            console.log('item', item, this.data);
            // 0已结束1未开始2进行中
            // 考试结果:null-未开始，0不合格，1合格
            if (item.status === 0 || item.pass === 0 || item.pass === 1) { // 去详情 postTrainingDetail
                this.$router.push({path: `/postTrainingDetail?resId=${item.resId}&id=${this.$route.query.id}&appTkhId=${this.data.appTkhId}&type=${item.type}`});
            } else if (item.status === 2) { // 去考试
                if (item.ifStartExam) {
                    // 判断是否最大打开次数
                    this.$axios({
                        method: 'GET',
                        url: '/app/api/trainee/course/train/checkOpenCount',
                        params: {
                            itmId: this.$route.query.id,
                            resModId: item.resId,
                            tkhId: this.data.appTkhId
                        }
                    }).then((res) => {
                        if (res.data.errCode === 'success') {
                            // 获取考试详情
                            this.$axios({
                                method: 'GET',
                                url: `/app/api/trainee/train/detail/${this.$route.query.id}`,
                                params: {
                                    resId: item.resId
                                }
                            }).then((data) => {
                                this.currentItem = {
                                    ...item,
                                    ...data.data
                                };
                                // 判断是否正在评分
                                this.checkTestPrev(item.resId);
                            });
                        }
                    }).catch(err => {
                        Notify({
                            message: err.response.data.errMsg,
                            color: '#fff',
                            background: '#D9001B'
                        });
                    });
                } else {
                    Notify({
                        message: this.$t('not_started_or_ended'),
                        color: '#fff',
                        background: '#ffc002'
                    });
                }
            } else if (item.status === 1) { // 未开始
                Notify({
                    message: this.$t('exam_has_not_yet_started'),
                    color: '#fff',
                    background: '#ffc002'
                });
            }
        },
        // 判断是否正在评分
        checkTestPrev(resId) {
            this.$axios({
                method: 'GET',
                url: '/app/module/check-test-prev',
                params: {
                    modId: resId
                }
            }).then((result) => {
                this.examTip = true;
                console.log('result', result);
            }).catch(() => {
                this.examTip = false;
                // Notify({
                //     message: err.response.data.errMsg,
                //     color: '#fff',
                //     background: '#D9001B'
                // });
            });
        }
    },
    mounted() {
        this.getFreshDetail();
    },
    watch: {
    }
};
</script>

<style scoped lang="less">
  .list-box{
    background: #fff;
    padding: 0 20px;
    margin-top: 10px;
    .item-box{
      border-bottom: 1px solid #eee;
      display: flex;
      justify-content: space-between;
      align-items: end;
      padding: 15px 0;
      align-items: center;
      .box-right{
        white-space: nowrap;
        padding-left: 10px;
      }
    }
  }
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  /deep/.van-dialog__content{
    margin: 0 20px;
  }
/deep/.van-dialog__header {
    font-size: 20px;
    margin-left: 20px;
    text-align: initial;
}
</style>
